package com.weilive.push.service.apns;

import java.util.Date;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.locks.ReentrantLock;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;

import com.notnoop.apns.APNS;
import com.notnoop.apns.ApnsService;
import com.weilive.core.cache.redis.RedisConfig;
import com.weilive.core.cache.redis.RedisService;
import com.weilive.core.utils.FileUtils;
import com.weilive.push.ServerContext;

public class ApnsInactiveDevice implements Runnable {
	private static final Logger logger = LoggerFactory.getLogger(ApnsPusher.class);
	private static RedisService redis;

	private static Set<String> inactiveDevices;

	private static ReentrantLock lock = new ReentrantLock();

	public ApnsInactiveDevice(ApplicationContext context) {
		redis = context.getBean(RedisService.class);
		inactiveDevices = redis.set(RedisConfig.IOS_INACTIVE_DEVICE_TOKENS);
	}

	// 发送
	private static ApnsService service = ServerContext.isWorkingEnv()
			? APNS.newService().asPool(1).withCert(FileUtils.getResourcePath(ServerContext.getApnsProd()), "12677484")
					.withProductionDestination().build()
			: APNS.newService().asPool(1).withCert(FileUtils.getResourcePath(ServerContext.getApnsDev()), "12677484")
					.withSandboxDestination().build();

	@Override
	public void run() {
		long begin = System.currentTimeMillis();
		int size = 0;
		try {
			Map<String, Date> tokens = service.getInactiveDevices();
			size = tokens.size();
			lock.lock();
			for (String token : tokens.keySet()) {
				// 获取失效的token,放入redis缓存
				redis.sadd(RedisConfig.IOS_INACTIVE_DEVICE_TOKENS, token);

				// 加入内存
				inactiveDevices.add(token);
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			lock.unlock();
		}
		logger.info("IOS---->load过期token数据成功,size={},耗时={}ms", size, (System.currentTimeMillis() - begin));
	}

	public static Set<String> getInactiveDevices() {
		lock.lock();
		try {
			return inactiveDevices;

		} finally {
			lock.unlock();
		}
	}

	public static void addInactiveDevice(String token) {
		lock.lock();
		try {
			// 获取失效的token,放入redis缓存
			redis.sadd(RedisConfig.IOS_INACTIVE_DEVICE_TOKENS, token);
			// 加入内存
			inactiveDevices.add(token);

		} finally {
			lock.unlock();
		}
	}
}
